package com.boyou.sytzc.utils.common

import com.boyou.sytzc.core.appctx.AppData.IMAGE_CACHE_PATH
import kotlin.Throws
import java.lang.Exception
import android.content.Context
import com.boyou.sytzc.core.appctx.AppData
import java.io.File
import android.os.Environment
import android.os.Build
import android.text.format.DateFormat
import com.baidu.location.LocationClientOption.LocationMode
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import java.lang.Thread
import java.lang.Runnable
import com.boyou.sytzc.utils.common.CommonUtil
import java.util.*

/**
 * Created by Cosecant on 2015/9/16.
 */
object CommonUtil {

    /** 初始化应用 **/
    fun initApplication(context: Context): Boolean {
        //获取APP files目录
        AppData.CACHE_PATH = context.filesDir.canonicalPath + "/syt/"
        val cacheDir = File(AppData.CACHE_PATH)
        if (cacheDir.mkdirs() || cacheDir.isDirectory) return true
        //获取SD卡目录
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) AppData.CACHE_PATH =
                Environment.getExternalStorageDirectory().canonicalPath + "/syt/" else AppData.CACHE_PATH =
                context.cacheDir.canonicalPath + "/syt/"
        }
        val cacheDir1 = File(AppData.CACHE_PATH)
        if (cacheDir1.mkdirs() || cacheDir1.isDirectory) return true //创建目录文件夹
        //获取App缓存目录
        AppData.CACHE_PATH = context.cacheDir.canonicalPath + "/syt/"
        val cacheDir2 = File(AppData.CACHE_PATH)
        return cacheDir2.mkdirs() || cacheDir2.isDirectory
    }

    /**
     * 获取当前的位置
     *
     * @param context
     * @param scanSpanTime
     * @param mode
     * @param listener
     */
    @JvmStatic
    fun getCurrentLocation(
        context: Context?,
        scanSpanTime: Int,
        mode: LocationMode?,
        listener: BDAbstractLocationListener?
    ) {
        val locationClient = LocationClient(context)
        locationClient.registerLocationListener(listener)
        locationClient.locOption = LocationClientOption().apply {
            locationMode = mode //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
            setCoorType("bd09ll") //可选，默认gcj02，设置返回的定位结果坐标系
            setScanSpan(scanSpanTime) //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
            setIsNeedAddress(true) //可选，设置是否需要地址信息，默认不需要
            isOpenGps = true //可选，默认false,设置是否使用gps
            isLocationNotify = true //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
            setIsNeedLocationDescribe(true) //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
            setIsNeedLocationPoiList(true) //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
            setIgnoreKillProcess(false) //可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
            SetIgnoreCacheException(false) //可选，默认false，设置是否收集CRASH信息，默认收集
            setEnableSimulateGps(false) //可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        }
        if (!locationClient.isStarted)
            locationClient.start() //请求位置
        else locationClient.requestLocation()
    }

    /** 清理数据缓存 **/
    @JvmStatic
    fun clearCache() = Thread {
        try {
            val today = DateFormat.format("yyyyMMdd", Date()).toString()
            val calendar = Calendar.getInstance()
            calendar.time = Date()
            calendar.add(Calendar.DATE, -1)
            val yesterday = DateFormat.format("yyyyMMdd", calendar).toString()
            val imageCacheFile = File(IMAGE_CACHE_PATH)
            if (imageCacheFile.exists()) {
                val files = imageCacheFile.listFiles()
                if (files != null && files.isNotEmpty()) {
                    for (folder in files) {
                        if (folder.name == today || folder.name == yesterday) continue
                        deleteFolder(folder)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }.start()

    /** 删除文件夹 **/
    @JvmStatic
    fun deleteFolder(folder: File) {
        when {
            folder.isFile -> folder.delete()
            folder.isDirectory -> {
                val children = folder.listFiles()
                if (children != null && children.isNotEmpty()) {
                    for (child in children) {
                        deleteFolder(child)
                    }
                }
                folder.delete()
            }
        }
    }
}